package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.vo.GoodsDetailCommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 鲸落
 * @Date: 2024/05/21/20:35
 * @Version: 1.0
 * @Description:
 */
@Service
public class WxGoodsServiceImpl_YYH implements WxGoodsService_YYH {
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCollectMapper collectMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketGoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    @Override
    public MarketGoods selectGoodsById(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<MarketGoods> selectGoodsByCategory(Integer categoryId, Integer relatedGoodsNum) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(categoryId);
        List<MarketGoods> goodsList = goodsMapper.selectByExampleSelective(goodsExample, MarketGoods.Column.id,
                MarketGoods.Column.isHot, MarketGoods.Column.isNew, MarketGoods.Column.name, MarketGoods.Column.brief,
                MarketGoods.Column.counterPrice, MarketGoods.Column.picUrl, MarketGoods.Column.retailPrice);
        if(goodsList.size() <= relatedGoodsNum){
            return goodsList;
        }else {
            return goodsList.stream().limit(6).collect(Collectors.toList());
        }
    }

    @Override
    public Map<String, Object> detail(Integer goodsId) {
        // 传入的id为goodsId
        Map<String, Object> data = new HashMap<>();
        // goods的信息
        MarketGoods goods = selectGoodsById(goodsId);
        data.put("info", goods);
        // 已经收藏该商品的用户数量
        Integer userHasCollect = getUserHasCollect(goodsId);
        data.put("userHasCollect", userHasCollect);
        // 后台管理中的通用问题
        List<MarketIssue> issue= getIssue();
        data.put("issue", issue);
        // 商品评论 注意按照响应结果的格式来封装
        Map<String,Object> comment= getCommentByGoodsId(goodsId);
        data.put("comment", comment);
        // 规格列表 goods_specification表 → 注意按照响应结果的格式来封装
        List<Map<String,Object>> specificationList = getGoodsSpecificationListByGoodsId(goodsId);
        data.put("specificationList", specificationList);
        // 货品信息 goods_product表
        List<MarketGoodsProduct> productList = getGoodsProductListByGoodsId(goodsId);
        data.put("productList", productList);
        // 参数信息 goods_attribute表
        List<MarketGoodsAttribute> attribute = getGoodsAttributeListByGoodsId(goodsId);
        data.put("attribute", attribute);
        // 制造商信息
        MarketBrand brand = getBrandByBrandId(goods.getBrandId());
        data.put("brand", brand);
        // 是否分享 system表中name=market_wx_share
        Boolean share = getShare();
        data.put("share", share);
        // 商品分享图片地址
        data.put("shareImage", goods.getShareUrl());
        return data;
    }

    private Boolean getShare() {
        MarketSystem system = systemMapper.selectByPrimaryKey(5);
        String keyValue = system.getKeyValue();
        if("true".equals(keyValue)){
            return true;
        }else {
            return false;
        }
    }

    private MarketBrand getBrandByBrandId(Integer brandId) {
        return brandMapper.selectByPrimaryKey(brandId);
    }

    private List<MarketGoodsAttribute> getGoodsAttributeListByGoodsId(Integer goodsId) {
        MarketGoodsAttributeExample goodsProductExample = new MarketGoodsAttributeExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        return goodsAttributeMapper.selectByExample(goodsProductExample);
    }

    private List<MarketGoodsProduct> getGoodsProductListByGoodsId(Integer goodsId) {
        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        return goodsProductMapper.selectByExample(goodsProductExample);
    }

    private List<Map<String, Object>> getGoodsSpecificationListByGoodsId(Integer goodsId) {
        MarketGoodsSpecificationExample goodsSpecificationExample = new MarketGoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsSpecification> goodsSpecifications = specificationMapper.selectByExample(goodsSpecificationExample);
        // 按照specification字段进行分组,数据形式是map
        Map<String, List<MarketGoodsSpecification>> specificationMap = goodsSpecifications.stream().collect(Collectors.groupingBy(MarketGoodsSpecification::getSpecification));
        // 要返回的结果
        List<Map<String, Object>> specificationList = new ArrayList<>();
        // 遍历specificationMap，然后嵌套遍历List<MarketGoodsSpecification>
        for (String key : specificationMap.keySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name",key);
            map.put("valueList",specificationMap.get(key));
            specificationList.add(map);
        }
        return specificationList;
    }

    private Map<String, Object> getCommentByGoodsId(Integer goodsId) {

        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(goodsId);
        List<MarketComment> commentList = commentMapper.selectByExample(commentExample);
        if(commentList.size() == 0){
            return null;
        }
        // 整合对当前商品评论的所有userId
        List<Integer> userIdList = new ArrayList<>();
        for (MarketComment comment : commentList) {
            Integer userId = comment.getUserId();
            userIdList.add(userId);
        }
        // 查询user表，构造userID-nickname和userId-avatar的map
        MarketUserExample userExample = new MarketUserExample();
        userExample.createCriteria().andIdIn(userIdList);
        List<MarketUser> commentUserList = userMapper.selectByExample(userExample);
        Map<Integer,String> commentUserIdAndNicknameMap = new HashMap<>();
        Map<Integer,String> commentUserIdAndAvatarMap = new HashMap<>();
        for (MarketUser user : commentUserList) {
            commentUserIdAndNicknameMap.put(user.getId(),user.getNickname());
            commentUserIdAndAvatarMap.put(user.getId(),user.getAvatar());
        }
        // 要填充的数据
        List<GoodsDetailCommentVo> commentVoList = new ArrayList<>();
        for (MarketComment comment : commentList) {
            GoodsDetailCommentVo goodsDetailCommentVo = new GoodsDetailCommentVo();
            goodsDetailCommentVo.setId(comment.getId());
            goodsDetailCommentVo.setNickname(commentUserIdAndNicknameMap.get(comment.getUserId()));
            goodsDetailCommentVo.setContent(comment.getContent());
            goodsDetailCommentVo.setAvatar(commentUserIdAndAvatarMap.get(comment.getUserId()));
            goodsDetailCommentVo.setAdminContent(comment.getAdminContent());
            goodsDetailCommentVo.setAddTime(comment.getAddTime());
            goodsDetailCommentVo.setPicList(comment.getPicUrls());
            commentVoList.add(goodsDetailCommentVo);
        }
        // 最终返回的数据
        Map<String,Object> comments = new HashMap<>();
        comments.put("count",commentList.size());
        comments.put("data",commentVoList.stream().limit(2).collect(Collectors.toList()));
        return comments;
    }

    private List<MarketIssue> getIssue() {
        return issueMapper.selectByExample(new MarketIssueExample());
    }

    private Integer getUserHasCollect(Integer goodsId) {
        // 查询collect表
        MarketCollectExample collectExample = new MarketCollectExample();
        collectExample.createCriteria().andValueIdEqualTo(goodsId);
        List<MarketCollect> goodsCollects = collectMapper.selectByExample(collectExample);
        return goodsCollects.size();
    }
}
